<template>
  <el-drawer
      v-model="drawer"
      size="700px"
      :with-header="false"
      @closed="saveConfig"
  >
    <el-tabs class="tabs" v-model="showTab">
      <el-tab-pane name="base" :label="(single?'单人':'多人')+'办理设置'" class="pane">
        <div class="title">
          <b>节点名称</b>
        </div>
        <el-input v-model="name" placeholder="输入节点的名称..." clearable />
        <br/>
        <div v-if="single">
          <div class="title top30">
            <b>单人办理方式</b>
            <span>流程走到当前节点时，采取什么行为进行处理</span>
          </div>
          <el-radio-group v-model="hissBusinessSingleMode">
            <el-radio label="manual">人工审批</el-radio>
            <el-radio label="approval">自动通过</el-radio>
            <el-radio label="rejection">自动拒绝</el-radio>
          </el-radio-group
          ><br/>
        </div>
        <div v-else>
          <div class="title top30">
            <b>多人办理方式</b>
            <span>流程走到当前节点时，采取什么行为进行处理</span>
          </div>
          <el-radio-group v-model="hissBusinessMultipleMode">
            <el-radio label="sequential">串签（按顺序以此审批）</el-radio>
            <el-radio label="parallel">并签（需要所有审批人同意）</el-radio>
            <el-radio label="or1">或签1（一人同意即可）</el-radio>
            <el-radio label="or2">或签2（二人同意即可）</el-radio>
            <el-radio label="or3">或签3（三人同意即可）</el-radio>
            <el-radio label="or5">或签5（>50%的人同意即可）</el-radio>
          </el-radio-group><br/>
        </div>
        <div v-if="hissBusinessSingleMode=='manual'">
          <div class="title top30">
            <b>审批人为空时</b>
            <span>没有审批人、候选人时处理逻辑</span>
          </div>
          <el-radio-group v-model="hissBusinessNullNodeMode">
            <el-radio label="1">直接通过</el-radio>
            <el-radio label="0">挂起</el-radio>
          </el-radio-group><br/>
          <div class="title top30">
            <b>办理人对象</b>
            <span>常用的办理人</span>
          </div>
          <el-radio-group v-model="hissBusinessSingleUser" @change="singleUserChange">
            <el-radio v-for="item in singleUserVariableList" :label="item.key">{{item.description}}</el-radio>
          </el-radio-group>
          <br/>
          <div v-if="selectMode.inputType=='TREEQUERY'">
            <el-divider />
            <div class="title title-line">
              <b>添加{{selectMode.name}}</b>
              <span>{{ selectMode.selectMax>0?'最多不超过'+selectMode.selectMax+'个'+selectMode.name:'无个数限制' }}</span>
            </div>
            <el-button icon="Plus"  @click="handleSelectShow">
              选择{{selectMode.name}}
            </el-button>
            <el-tag v-for="tag in selectMode.selectList" :key="tag.name" class="mx-1"  closable  @close="selectMode.close(tag)">{{ tag.name }}</el-tag>
          </div>
          <div v-if="selectMode.inputType=='SELECTQUERY'">
            <el-divider />
            <div class="title title-line">
              <b>添加{{selectMode.name}}</b>
              <span>{{ selectMode.selectMax>0?'最多不超过'+selectMode.selectMax+'个'+selectMode.name:'无个数限制' }}</span>
            </div>
            <SelectQuery :variable-type="selectMode.type" :title="selectMode.name" :tenant="tenant" :ok="selectMode.selectOk" :max="selectMode.selectMax" :init-data="selectMode.target.config"/>
          </div>
          <div v-if="selectMode.inputType=='INPUT'">
            <el-divider />
            <div class="title title-line">
              <b>添加{{selectMode.name}}</b>
            </div>
            <el-input v-model="selectMode.target.config" placeholder="输入自定义的表达式" />
          </div>
          <el-divider />
          <div class="title title-line">
            <b>设置可用的办理按钮</b>
            <span>如果不显示,前端永远不显示该按钮</span>
          </div>
          <ButtonConfig ref="bConfig" :attr="attr" :config="config" :id="id"/>
        </div>
      </el-tab-pane>
      <el-tab-pane name="form" label="表单权限">
        <FormConfig ref="fConfig" :tenant="tenant" :config="config" :can-add="true"/>
      </el-tab-pane>
      <SelectVariableDialog v-for="item in singleUserVariableTypeList"
                            :key="item.type"
                        :ref="item.type+'Ref'"
                        :max="item.selectMax"
                            :variable-type="item.type"
                            :tenant="tenant"
                        :ok="item.selectOk"
                            :title="item.name">
      </SelectVariableDialog>
    </el-tabs>
  </el-drawer>
</template>

<script>
import {queryTenantSingleUserVariable, queryTenantSingleUserVariableType} from "@/api/BusinessForDesignApi";
import FormConfig from './FormConfig'
import SelectVariableDialog from './SelectVariableDialog'
import SelectQuery from './SelectQuery'
import ButtonConfig from './ButtonConfig'
import {updateElementName} from "@/utils/UpdateElementUtil";

export default {
  name: "SingleApproveConfig",
  components:{SelectVariableDialog,SelectQuery,ButtonConfig,FormConfig},
  props:{
    tenant:{
      type:String,
      default:''
    },
    single:{//是否单人
      type:Boolean,
      default:true
    },
    config:{
      type: Object,
      default: {}
    },
    id:{
      type: String,
      default: ''
    },
    attr:{
      type: String,
      default: ''
    }
  },
  data() {
    return {
      name:'',
      showTab:'base',
      drawer:false,
      hissBusinessSingleMode:'manual',
      hissBusinessMultipleMode:'sequential',
      hissBusinessNullNodeMode:'0',// 节点为空时对应的处理方式
      hissBusinessSingleUser: '',
      singleUserVariableList:[],// 可用的自定变量
      singleUserVariableTypeList:[],// 自定义的变量类型
      // 当前是那种模式
      selectMode:''
    }
  },
  watch:{
    id:function (newVal,oldVal){
      if(newVal){
        if(this.drawer){
          this.initPanel()
        }
      }
    }
  },
  methods: {
    // 加载自定义变量
    async initSingleUserTypeList() {
      if (this.singleUserVariableList.length == 0) {
        let _this = this;
        let data = {
          _tenant: this.tenant
        }
        // 加载自定义变量
        await queryTenantSingleUserVariable(data).then(async res => {
          let temp = res.data.result;
          for (let i = 0; i < temp.length; i++) {
            let vr = temp[i]
            vr['ok'] = function (res) {
              vr['tempValue'] = res
            }
            vr['show'] = function () {
              _this.$refs[vr.value].show()
            }
          }
          await this.parseVariableTypeList(res)
          this.singleUserVariableList = temp
        })
      }
    },
    // 抽取所有的类型
    parseVariableTypeList(res){
      let temp = res.data.result;
      let tempIds = {}
      let newTemp = []
      let _this = this
      for (let i = 0; i < temp.length; i++) {
        let obt = temp[i]
        let vr = JSON.parse(JSON.stringify(obt.methodType))
        if(tempIds[vr.type]){// 已经解析过了，则跳过重复的
          continue
        }
        vr.target = '';
        if(vr.inputType=='SELECTQUERY') {//弹出树形选择
          vr.selectOk=function(result){// 确认选中
            _this.selectMode.target['config']=result
          }
        }
        if(vr.inputType=='TREEQUERY'){//弹出树形选择
          vr.selectMax = 1;
          vr.selectList = [];
          vr.selectOk=function(result){// 确认选中
            console.log("==============>:",result)
            _this.selectMode.selectList=result
            _this.selectMode.target['config']=result
          }
          vr.close=function(tag){//删除选中的函数
            for (let i = 0; i < _this.selectMode.selectList.length; i++) {
              let tempG = _this.selectMode.selectList[i]
              if(tempG.id==tag.id){
                _this.selectMode.selectList.splice(i,1)
                break
              }
            }
            if(_this.selectMode.target){
              _this.selectMode.target['config']=_this.selectMode.selectList
            }
          }
        }
        newTemp.push(vr)
      }
      this.singleUserVariableTypeList=newTemp
    },
    saveConfig(){
      if(!this.id||this.id==''){
        return
      }
      let nodeConfig = this.config.nodeConfig[this.id]||{};
      nodeConfig.hissBusinessSingleUser=this.hissBusinessSingleUser
      nodeConfig.hissBusinessSingleMode=this.hissBusinessSingleMode
      nodeConfig.hissBusinessMultipleMode=this.hissBusinessMultipleMode
      nodeConfig.hissBusinessNullNodeMode=this.hissBusinessNullNodeMode
      if(this.hissBusinessSingleMode=='manual'){
        nodeConfig.selectMode=JSON.parse(JSON.stringify(this.selectMode))
      }else{
        delete nodeConfig.selectMode
      }
      updateElementName(this.bpmnModeler,this.element,this.businessObject,this.name)
      this.config.nodeConfig[this.id]=nodeConfig
      this.$refs.fConfig.saveForm()
      if(this.$refs.bConfig){// 自动审批可能不存储在
        this.$refs.bConfig.saveButton()
      }
      let canvas = this.bpmnModeler.get("canvas");
      if(canvas){
        canvas.resized()
      }
    },
    // 显示并初始化值
    show(bpmnModeler,businessObject,element){
      this.drawer = true
      this.bpmnModeler = bpmnModeler
      this.element = element
      this.businessObject = businessObject;
    },
    // 开始初始化面板
    async initPanel() {
      let nodeConfig = this.config.nodeConfig[this.id] || {};
      this.name = this.businessObject.get('name')
      this.hissBusinessSingleUser = nodeConfig.hissBusinessSingleUser || ''
      this.hissBusinessSingleMode = nodeConfig.hissBusinessSingleMode || 'manual'
      this.hissBusinessMultipleMode = nodeConfig.hissBusinessMultipleMode || 'sequential'
      this.hissBusinessMultipleMode=nodeConfig.hissBusinessMultipleMode||'1'
      if (this.drawer) {
        this.$nextTick(() => {
          this.$refs.fConfig.initForm(this.id)
          if(this.$refs.bConfig){// 自动审批可能不存储在
            this.$refs.bConfig.initButton(this.id)
          }
        })
      }
      await this.initSingleUserTypeList()
      this.selectMode = nodeConfig.selectMode || {}
    },
    // 选择弹窗
    handleSelectShow(){
      let id = this.selectMode.type+'Ref'
      let ref = this.$refs[id];
      console.log("==========="+id,ref)
      if(ref){
        ref[0].show(this.selectMode.selectList)
      }
    },
    // 切换办理人
    singleUserChange(){
      this.selectMode={}
      for (let i = 0; i < this.singleUserVariableList.length; i++) {
        let temp = this.singleUserVariableList[i];
        if(temp.key==this.hissBusinessSingleUser){
          let modeName = temp.methodType.type;
          for (let j = 0; j < this.singleUserVariableTypeList.length; j++) {
            let tempType = this.singleUserVariableTypeList[j]
            if(tempType.type==modeName){
              this.selectMode = tempType
              tempType.target=temp;
              if(tempType.inputType=='TREEQUERY'||tempType.inputType=='SELECTQUERY'){
                tempType.selectMax = temp.maxSize>1?1:0;
                tempType.selectList = temp['config']||[]
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style>
.top30 {
  margin-top: 30px;
}
#tab-base,#tab-form {
  font-size: 16px;
  font-family:'微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑', sans-serif;
}
.pane{
  text-align: left;
}
.title{
  width: 100%;
}
.title b{
  font-size:14px;
  font-family:'微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑', sans-serif;
  font-weight:700;
  color: #000;
  display: block;
  margin: 8px 0px;
}
.title span{
  font-size:13px;
  font-family:'微软雅黑', sans-serif;
  font-weight:400;
  color:#999999;
  display: block;
}
.title-line{
  clear: both;
  margin-bottom: 10px;
  overflow: hidden;
}
.title-line b{
  display: inline-block;
  float: left;
}
.title-line span{
  display: inline-block;
  float: left;
  margin-top: 10px;
  margin-left: 15px;
}
</style>
